import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import SettingView from '../views/SettingView.vue'
import ProfileSettingView from '../views/ProfileSettingView.vue'
import NewArticleView from '../views/NewArticle.vue'
import MeView from '../views/MeView.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/me',
    name: 'me',
    component: MeView,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView,
  },
  {
    path: '/me/setting',
    name: 'setting',
    component: SettingView,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/me/profile',
    name: 'profile',
    component: ProfileSettingView,
    meta: {
      requiresAuth: true
    }
  },
  {
	path: '/newarticle',
	name: 'newarticle',
	component: NewArticleView,
	meta: {
		requiresAuth: true
	}
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  if (to.name === 'login' && localStorage._authing_token) {
    //前往登录页但是已经登陆
    next({path:'/'})
  } else {
    next() // 其余
  }
})

//https://stackoverflow.com/questions/52653337/vuejs-redirect-from-login-register-to-home-if-already-loggedin-redirect-from
//全局路由守卫,若未登陆则要求登陆
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!localStorage._authing_token) { //使用localStorage中的内容判断,store中的内容在刷新时会短暂消失
      next({ name: 'login' })
    } else {
      next() // go to wherever I'm going
    }
  } else {
    next() // does not require auth, make sure to always call next()!
  }
})

export default router
